package cn.edu.swu.datanalysis.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;

import cn.edu.swu.datanalysis.dao.ColAnalyzer;
import cn.edu.swu.datanalysis.entity.Record;
import cn.edu.swu.datanalysis.entity.Statistics;
import cn.edu.swu.datanalysis.entity.UploadedFile;
import cn.edu.swu.datanalysis.service.LoadDataService;
import cn.edu.swu.datanalysis.service.SplitPageService;
import cn.edu.swu.datanalysis.utils.DataExport;

@Controller
public class MainController {
	
	

	private static final Log logger = LogFactory.getLog(MainController.class);

	@Autowired
	private LoadDataService loadDataService;
	@Autowired
	private SplitPageService splitPageService;
	
	@RequestMapping("/home")
	public String home(){
		return "index";
	}

	@RequestMapping("/index")
	public String fileUpload(Model model) {
		model.addAttribute("uploadedFile", new UploadedFile());

		return "fileupload";
	}

	@RequestMapping("/fileupload")
	public String saveFile(HttpServletRequest request, @ModelAttribute UploadedFile uploadedFile,
			BindingResult bindingResult, Model model) {
		logger.info("start upload files");
		MultipartFile multipartFile = uploadedFile.getMultipartFile();

		String fileName = multipartFile.getOriginalFilename();
		String givenFileName = uploadedFile.getFileName();
		if (givenFileName != null && !givenFileName.isEmpty()) {
			fileName = givenFileName;
		}

		File file = new File(request.getServletContext().getRealPath("/file"), fileName);
		try {
			if (!file.exists())
				file.createNewFile();
			multipartFile.transferTo(file);

			loadDataService.loadData(file);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "result";
	}

	@RequestMapping("/filedownload")
	public void filedownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		/* file download settings */
		response.setContentType("text/comma-separated-values");
		response.addHeader("Content-Disposition", "attachment;filename=records.csv");
		/* save file to /data/records.csv and output to client */
		InputStream is = DataExport.exportData("mydb", "mycol", "csv",
				"a1,a2,a3,a4,a5,a6,a7,a8,a9,a10,a11,a12,quality");
		String outputFilePath = request.getServletContext().getRealPath("/data");
		File file = new File(outputFilePath, "records.csv");

		if (file.exists()) {
			file.delete();
			file.createNewFile();
		} else {
			file.createNewFile();
		}
		BufferedInputStream bis = new BufferedInputStream(is);
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
		BufferedOutputStream webOs = new BufferedOutputStream(response.getOutputStream());
		byte[] buffer = new byte[1024];

		while (bis.read(buffer) > 0) {
			bos.write(buffer);
			webOs.write(buffer);
		}
		webOs.flush();
		bos.flush();
		webOs.close();
		bos.close();
		bis.close();
		is.close();		
	}

	@RequestMapping("/showRecords")
	public String showRecords() {
		// List<Record> records = splitPageService.getRecords(pageNumber,
		// pageSize);
		// model.addAttribute("records",records);
		return "showRecords";
	}

	@RequestMapping(value = "/getRecords")
	public void getRecords(@RequestParam("pageNumber") int pageNumber, @RequestParam("pageSize") int pageSize,
			HttpServletResponse resp) {
		Gson gson = new Gson();
		List<Record> records = splitPageService.getRecords(pageNumber, pageSize);
		resp.setContentType("application/json");
		try {
			PrintWriter out = resp.getWriter();
			out.print(gson.toJson(records));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@RequestMapping("/analyzeCols")
	public String analyzeCols(Model model) {
		String[] colNames = { "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "quality" };

		ColAnalyzer analyzer = new ColAnalyzer();
		List<Statistics> statList = new ArrayList<Statistics>();
		for (String name : colNames) {
			statList.add(analyzer.analyzeCol(name));
		}
		model.addAttribute("statisticsList", statList);
		return "analyzeCols";
	}

}
